/*
 * Copyright (C) 2011  John Lawrence thegordo.john at gmail.com
 * Licensed under GPLv3 or later. see http://www.gnu.org/copyleft/gpl.html
 */

package org.jklawrencefam.server.smtp.command;

import org.jklawrencefam.server.smtp.SmtpCode;
import org.jklawrencefam.server.smtp.SmtpProtocol;
import org.jklawrencefam.server.smtp.state.SmtpState;

/**
 * User: John Lawrence
 * Date: 5/20/11
 * Time: 12:55 AM
 */
public abstract class SmtpCommand {
    protected String argumentString;
    protected SmtpState state;
    protected SmtpProtocol smtpProtocol;
    private boolean isValid;

    protected SmtpCommand(String CommandString) {
        if (CommandString.length() > 5) {
            this.argumentString = CommandString.substring(5);
        }
        processArgumentString();
        isValid = isValid();
    }

    public final void setState(SmtpState state) {
        this.state = state;
    }

    public final void doProcess() {
        if (isValid) {
            doProcessInternal();
        }
    }

    public void setProtocol(SmtpProtocol smtpProtocol) {
        this.smtpProtocol = smtpProtocol;
    }

    protected String composeMessage(SmtpCode code, String... message) {
        StringBuilder builder = new StringBuilder(code.getCode() + " " + smtpProtocol.getHostname());
        for (String messagePart : message) {
            builder.append(" ");
            builder.append(messagePart);
        }
        if (message.length == 0) {
            builder.append(" ");
            builder.append(code.getMessage());
        }
        return builder.toString();
    }

    public abstract String getReplyMessage();

    protected abstract boolean isValid();

    /**
     * This method should be overridden if the validity of the command depends on the argument string
     */
    protected void processArgumentString() {

    }

    /**
     * This method should be overridden if data from the argument needs to be saved.
     */
    protected void doProcessInternal() {
    }
}
